import React, { useMemo } from 'react';
import {
  View,
  StyleSheet,
} from 'react-native';
import MasonryCarousel from './MasonryCarousel';
import HorizontalImageScroll from './HorizontalImageScroll';
import SectionTitle from './SectionTitle';
import FoodCultureGrid from './FoodCultureGrid';
import {
  MasonrySkeletonLoader,
  HorizontalSkeletonLoader,
} from './SkeletonLoader';
import { COLORS } from '../styles/constants';

/**
 * 首页内容组件
 * @param {Object} props 组件属性
 * @param {string} props.city 城市名称
 * @param {Array} props.currentAttractions 当前景点列表
 * @param {Array} props.scenicAreasWithSpots 景区数据（大图标+小图标）
 * @param {boolean} props.scenicAreasLoading 景区数据加载状态
 * @param {Array} props.otherScenicAreas 周边景区数据
 * @param {boolean} props.otherScenicLoading 周边景区加载状态
 * @param {Array} props.foodCulture 美食文创列表
 * @param {boolean} props.foodCultureLoading 美食文创加载状态
 * @param {Array} props.provinceRecs 省内推荐列表
 * @param {Array} props.provinceTours 省内旅游路线列表
 * @param {boolean} props.provinceToursLoading 省内旅游路线加载状态
 * @param {Array} props.crossProvinceRoutes 跨省路线列表
 * @param {Array} props.crossProvinceTours 跨省旅游路线列表
 * @param {boolean} props.crossProvinceToursLoading 跨省旅游路线加载状态
 * @param {Function} props.onMasonryItemPress 瀑布流项目点击回调
 * @param {Function} props.onHorizontalItemPress 横向滚动项目点击回调
 * @param {Function} props.onFoodItemPress 美食项目点击回调
 * @param {Function} props.onFoodMorePress 美食更多按钮点击回调
 * @param {Function} props.onCurrentScenicPress 当前景区数量点击回调
 * @param {number} props.currentScenicCount 当前景区总数
 * @returns {JSX.Element} 内容组件
 */
export default function HomeContent({
  city,
  currentAttractions,
  scenicAreasWithSpots,
  scenicAreasLoading,
  otherScenicAreas,
  otherScenicLoading,
  foodCulture,
  foodCultureLoading,
  provinceRecs,
  provinceTours,
  provinceToursLoading,
  crossProvinceRoutes,
  crossProvinceTours,
  crossProvinceToursLoading,
  onMasonryItemPress,
  onHorizontalItemPress,
  onFoodItemPress,
  onFoodMorePress,
  onCurrentScenicPress,
  currentScenicCount = 0,
}) {
  // 优先展示后端返回的大小图景区数据（用于瀑布流展示）- 使用 useMemo 稳定引用
  const displayAttractions = useMemo(() => {
    if (scenicAreasWithSpots && scenicAreasWithSpots.length > 0) {
      return scenicAreasWithSpots;
    }
    return currentAttractions;
  }, [scenicAreasWithSpots, currentAttractions]);

  return (
    <View style={styles.container}>
      {/* 当前城市或景区（优先使用大小图接口返回的数据） */}
      {scenicAreasLoading && displayAttractions.length === 0 ? (
        <>
          <SectionTitle 
            title="当前景区" 
            count={currentScenicCount}
            onCountPress={onCurrentScenicPress}
          />
          <MasonrySkeletonLoader />
        </>
      ) : displayAttractions.length > 0 ? (
        <>
          <SectionTitle 
            title="当前景区" 
            count={currentScenicCount}
            onCountPress={onCurrentScenicPress}
          />
          <MasonryCarousel
            items={displayAttractions
              .map((a, idx) => {
                const img =
                  a.coverImage ||
                  a.image ||
                  'https://via.placeholder.com/600x400?text=%E6%99%AF%E5%8C%BA';
                const title = a.areaName || a.name || '';
                const distance = a.distance;
                const level = a.level;
                return {
                  image: img,
                  title,
                  id: a.id || String(idx),
                  distance,
                  level,
                  raw: a,
                };
              })
              .filter(
                it => typeof it.image === 'string' && it.image.length > 0,
              )}
            onPress={onMasonryItemPress}
          />
        </>
      ) : null}

      {/* 周边景区（使用 getOtherScenicAreas） */}
      {otherScenicLoading &&
        (!otherScenicAreas || otherScenicAreas.length === 0) ? (
        <>
          <SectionTitle title="周边景区" />
          <HorizontalSkeletonLoader />
        </>
      ) : Array.isArray(otherScenicAreas) && otherScenicAreas.length > 0 ? (
        <>
          <SectionTitle title="周边景区" />
          <HorizontalImageScroll
            items={otherScenicAreas
              .map((a, i) => {
                const img =
                  a.coverImage ||
                  a.image ||
                  'https://via.placeholder.com/400x300?text=%E6%99%AF%E5%8C%BA';
                const title = a.areaName || a.name || '';
                const distance = a.distanceKm ? `${a.distanceKm}km` : null;
                const level = a.level;
                return {
                  id: a.id || String(i),
                  image: img,
                  title,
                  distance,
                  level,
                  raw: a,
                };
              })
              .filter(
                it => typeof it.image === 'string' && it.image.length > 0,
              )}
            onPress={onHorizontalItemPress}
          />
        </>
      ) : null}

      {/* 美食文创 */}
      {foodCultureLoading && (!foodCulture || foodCulture.length === 0) ? (
        <>
          <SectionTitle
            title="美食·文创"
            showMore
            onPressMore={onFoodMorePress}
          />
          <HorizontalSkeletonLoader />
        </>
      ) : foodCulture.length > 0 ? (
        <>
          <SectionTitle
            title="美食·文创"
            showMore
            onPressMore={onFoodMorePress}
          />
          <FoodCultureGrid
            data={foodCulture}
            scrollEnabled={false}
            onPressItem={onFoodItemPress}
          />
        </>
      ) : null}

      {/* 省内推荐旅游路线（优先使用 getProvinceTours 接口数据） */}
      {provinceToursLoading &&
        (!provinceTours || provinceTours.length === 0) &&
        provinceRecs.length === 0 ? (
        <>
          <SectionTitle title="省内推荐旅游路线" />
          <HorizontalSkeletonLoader />
        </>
      ) : Array.isArray(provinceTours) && provinceTours.length > 0 ? (
        <>
          <SectionTitle title="省内旅游路线" />
          <HorizontalImageScroll
            items={provinceTours.map((a, i) => ({
              id: a.id || String(i),
              image:
                a.coverImage ||
                a.image ||
                'https://via.placeholder.com/400x300?text=%E6%97%85%E6%B8%B8%E8%B7%AF%E7%BA%BF',
              title: a.tourName || a.routeName || a.name || a.title || '',
              distance: a.distance,
              level: a.level,
              raw: a,
            }))}
            onPress={onHorizontalItemPress}
          />
        </>
      ) : provinceRecs.length > 0 ? (
        <>
          <SectionTitle title="省内推荐旅游路线" />
          <HorizontalImageScroll
            items={provinceRecs.map((a, i) => ({
              id: a.id || String(i),
              image: a.image,
              title: a.name,
              distance: a.distance,
              level: a.level,
              raw: a,
            }))}
            onPress={onHorizontalItemPress}
          />
        </>
      ) : null}

      {/* 跨省旅游线路（优先使用 getCrossProvinceTours 接口数据） */}
      {crossProvinceToursLoading &&
        (!crossProvinceTours || crossProvinceTours.length === 0) &&
        crossProvinceRoutes.length === 0 ? (
        <>
          <SectionTitle title="跨省旅游线路" />
          <HorizontalSkeletonLoader />
        </>
      ) : Array.isArray(crossProvinceTours) && crossProvinceTours.length > 0 ? (
        <>
          <SectionTitle title="跨省旅游线路" />
          <HorizontalImageScroll
            items={crossProvinceTours.map((a, i) => ({
              id: a.id || String(i),
              image:
                a.coverImage ||
                a.image ||
                'https://via.placeholder.com/400x300?text=%E8%B7%A8%E7%9C%81%E8%B7%AF%E7%BA%BF',
              title: a.tourName || a.routeName || a.name || a.title || '',
              distance: a.distance,
              level: a.level,
              raw: a,
            }))}
            onPress={onHorizontalItemPress}
          />
        </>
      ) : crossProvinceRoutes.length > 0 ? (
        <>
          <SectionTitle title="跨省旅游线路" />
          <HorizontalImageScroll
            items={crossProvinceRoutes.map((a, i) => ({
              id: a.id || String(i),
              image: a.image,
              title: a.name,
              distance: a.distance,
              level: a.level,
              raw: a,
            }))}
            onPress={onHorizontalItemPress}
          />
        </>
      ) : null}
      {/* 底部空白区域 */}
      <View style={styles.footerSpace}>{/* 这里可以添加公司logo */}</View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  footerSpace: {
    height: 100,
    backgroundColor: COLORS.transparent,
  },
});
